package models

import (
	"errors"
	"github.com/beego/beego/v2/client/orm"
)

type ErpSuppliers struct {
	Id                    int64
	DepartmentId          int64
	Name                  string
	Tel                   string
	Address               string
	Contacts              string
	Status                int
	PayMode               int
	PayMethod             int
	DeliveryMode          int
	GspCertificate        string
	GspCertificateEnddate string
	Summary               string
}

//查询
type ErpSuppliersQueryParam struct {
	BaseQueryParam
	Filter       string
	DepartmentId int64
}

func (a *ErpSuppliers) TableName() string {
	return ErpSuppliersTableName()
}

func ErpSuppliersTableName() string {
	return TableName("erp_suppliers")
}

func GetErpSuppliersById(id int64) (*ErpSuppliers, error) {

	r := new(ErpSuppliers)
	err := orm.NewOrm().QueryTable(ErpSuppliersTableName()).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}

	return r, nil

}

func ErpSuppliersList(params *ErpSuppliersQueryParam) []*ErpSuppliers {
	ls := make([]*ErpSuppliers, 0)
	query := orm.NewOrm().QueryTable(ErpSuppliersTableName())
	query = query.Filter("status", 0).Filter("department_id", params.DepartmentId)

	query.OrderBy("-Id").All(&ls)
	return ls
}

func ErpSuppliersPageList(params *ErpSuppliersQueryParam) ([]*ErpSuppliers, int64) {

	ls := make([]*ErpSuppliers, 0)

	query := orm.NewOrm().QueryTable(ErpSuppliersTableName())

	if len(params.Filter) > 0 {
		query = query.Filter("name__contains", params.Filter)
	}

	query = query.Filter("department_id", params.DepartmentId)

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

func ErpSuppliersAdd(c *ErpSuppliers) (int64, error) {

	c.Status = 0
	c.Name = c.Name

	return orm.NewOrm().Insert(c)
}

func (a *ErpSuppliers) ErpSuppliersEdit(filter ...string) error {

	if _, err := orm.NewOrm().Update(a, filter...); err != nil {
		return err
	}
	return nil
}

func ErpSuppliersDel(id, depid int64) error {

	var c ErpSuppliers
	c = ErpSuppliers{Id: id}

	orm.NewOrm().Read(&c)
	if c.Status == 1 {
		c.Status = 0
	} else {
		c.Status = 1
	}
	if c.DepartmentId != depid {
		return errors.New("数据不存在")
	}

	if _, err := orm.NewOrm().Update(&c, "status"); err != nil {
		return err
	}
	return nil
}
